﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ysb.Components;
using BLL;
using Model;
using System.Xml;
public partial class Admin_BillSepEdit : System.Web.UI.Page
{
    public string Mg;
    public string NotMg;
    public string IsMg;
    public string BaozhuangFL;
    public string DaigouFl;

    Tools tool = new Tools();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!AdminCheck.Check(this, 1))
        {
            Response.Redirect(AdminCheck.RedirectPage);
            return;
        }
        if (!Page.IsPostBack)
        {


            if (Request.QueryString["SepNo"] == null && Request.QueryString["SepNo"].ToString().Trim() == "")
            {

                Jscript.AlertAndGoBack("请按正常操作单据！");
                return;
            }
            XmlDocument Document = new XmlDocument();
            Document.Load(ApplicationInfo.PhysicalApplicationPath + "Config/AppConfig.config");
            Mg = Document.GetElementsByTagName("set1").Item(0).Attributes["value"].Value;
            NotMg = Document.GetElementsByTagName("set2").Item(0).Attributes["value"].Value;

            BindDDL();
            BindWallBill(Request.QueryString["SepNo"].ToString());
    
            BinDataState(Request.QueryString["SepNo"].ToString());
            BindLiuYan(Request.QueryString["SepNo"].ToString());

        }
    }

 
    void GetUser(string id)
    {

        DataTable dt = new PublicSqlService().GetData("*", "TblUserInfo", "Uid=" + id);
        if (dt.Rows.Count == 0)
        {
            Tools.OpenWindow(this, "公司信息异常，请联系管理人员");
            return;
        }
        sendertxt.Value = dt.Rows[0]["TrueName"].ToString();
        phonenotxt.Value = dt.Rows[0]["Tel"].ToString();
        companytxt.Value = dt.Rows[0]["Company"].ToString();
        addtxt.Value = dt.Rows[0]["Address"].ToString();
        creaduser.Value = id;
        if (dt.Rows[0]["Country"].ToString().Trim() == "美国")
        {
            IsMg = "true";
        }
        else
        {
            IsMg = "false";
        }
        DataTable ndt = new PublicSqlService().GetData("*", "Tb_UserProperty", "UserID=" + id);

        BaozhuangFL = ndt.Rows[0]["PackagingRate"].ToString();
        DaigouFl = ndt.Rows[0]["ShoppingServiceRate"].ToString();


    }
    void BinDataState(string tn)
    {

        Sataterp.DataSource = new PublicSqlService().GetData("*", "Tbl_BillStateRec", "SepNo='" + tn + "'");
        Sataterp.DataBind();
    }
    void BindLiuYan(string tn)
    {
        lyshow.DataSource = new PublicSqlService().GetData("*", "Tbl_Discuss", "Tno='" + tn + "'");
        lyshow.DataBind();
    }

    void BindWallBill(string tn)
    {

        DataTable dt = new PublicSqlService().GetData("*", "Tbl_SepBill", "SepNo='" + tn.Trim() + "'");
        if (dt.Rows.Count != 1)
        {
            Jscript.AlertAndGoBack("单据单号：" + tn + " 数据异常！请重新进入当前页面或记录单号联系管理人员！");
            return;
        }
        BindHuoWu(tn);
        tnlb.Text = "分单：&nbsp;" + tn + "&nbsp;&nbsp;运单： &nbsp;" + dt.Rows[0]["TrackingNo"].ToString();

        GetUser(dt.Rows[0]["CreateUserID"].ToString());//人员绑定
     //   jifeitype.DataSource = new PayModelService().GetUserCalType(dt.Rows[0]["CreateUserID"].ToString());
		
		DataTable table1 = new PayModelService().GetUserCalType(dt.Rows[0]["CreateUserID"].ToString());   
		table1.Columns.Add("bbb", System.Type.GetType("System.String"), "name+'-'+Substring(cid,3,10)"); 
		jifeitype.DataSource = table1;
		
        jifeitype.DataTextField = "bbb";
        jifeitype.DataValueField = "cid";
        jifeitype.DataBind();
        #region   发送人基本属性
        sendertxt.Value = dt.Rows[0]["SendBy"].ToString();

        phonenotxt.Value = dt.Rows[0]["USATelNo"].ToString();
        companytxt.Value = dt.Rows[0]["USACompany"].ToString();
        addtxt.Value = dt.Rows[0]["USAAddress"].ToString();
        #endregion
        #region   收件人基本属性
        renametxt.Value = dt.Rows[0]["CHNReceiver"].ToString();
        rephonenotxt.Value = dt.Rows[0]["CHNTelNo"].ToString();
        recompanytxt.Value = dt.Rows[0]["CHNCompany"].ToString();
        readdtxt.Value = dt.Rows[0]["CHNAddress"].ToString();
        #endregion
        #region 其他相关属性
        FlightNotxt.Value = dt.Rows[0]["FlightNo"].ToString();//参考
        AerialNotxt.Value = dt.Rows[0]["AerialNo"].ToString();//航空单号
        qyd_ddr.Text = dt.Rows[0]["Origin"].ToString();
        mdd_ddr.Text = dt.Rows[0]["Dest"].ToString();
        Descriptiontxt.Value = dt.Rows[0]["Description"].ToString();
        //支付方式

        paylist.Text = dt.Rows[0]["PayType"].ToString();
 
        //包装形式

        huowulist.Text = dt.Rows[0]["Packing"].ToString();
        #endregion
        #region 质量 体积

        zhongliang_txt.Value = dt.Rows[0]["Weight"].ToString();//重重量
        gaotxt.Value = dt.Rows[0]["MeasurementH"].ToString();
        changtxt.Value = dt.Rows[0]["MeasurementL"].ToString();
        kuantxt.Value = dt.Rows[0]["MeasurementW"].ToString();

        tijizhonglianghd.Value = dt.Rows[0]["DimensionsWeight"].ToString();

        #endregion
        #region  价格
        ChargedWt.Text = dt.Rows[0]["ChargedWt"].ToString(); //收费重量
        shoufeizhonglianghd.Value = dt.Rows[0]["ChargedWt"].ToString();
        FreightChargelb.Text = dt.Rows[0]["FreightCharge"].ToString();  //重量收费
        zlshoufeihd.Value = dt.Rows[0]["FreightCharge"].ToString();
        haiguanall.Text = dt.Rows[0]["TotalMoney"].ToString(); //海关申报总价
        haiguanhd.Value = dt.Rows[0]["TotalMoney"].ToString();
        dianfufeilb.Value = dt.Rows[0]["Memo2"].ToString();//垫付费

        daigoufeilb.Text = dt.Rows[0]["Memo3"].ToString();  //代购费

        daigoufeihd.Value = dt.Rows[0]["Memo3"].ToString();
        baozhuangfeilb.Text = dt.Rows[0]["Memo4"].ToString(); //包装费
        baozhuangfeihd.Value = dt.Rows[0]["Memo4"].ToString();
        guanshuitxt.Value = dt.Rows[0]["Duties"].ToString();  //关税
        baoxianfeitxt.Value = dt.Rows[0]["Premium"].ToString();//保险费
        othertxt.Value = dt.Rows[0]["OtherCharge"].ToString(); ;//其他费用
        youhuitxt.Value = dt.Rows[0]["Memo5"].ToString();  //优惠
        Totallb.Text = dt.Rows[0]["Total"].ToString();  //总费用
        Totalhb.Value = dt.Rows[0]["Total"].ToString();
        paytypehd.Value = dt.Rows[0]["Memo1"].ToString();  //计费类别

        string text = new WayBillService().GetCalTypeName(new Tools().StringToIntDif(dt.Rows[0]["Memo1"]).ToString());
        jifeitype.SelectedIndex = jifeitype.Items.IndexOf(jifeitype.Items.FindByText(text));


        if (dt.Rows[0]["State"].ToString().Trim() != "1")
        {
            delbtn.Enabled = false;
        }
        #endregion








    }
    //起运地 目的地
    void BindDDL()
    {
        qyd_ddr.DataSource = new PlaceService().GetStart();
        qyd_ddr.DataTextField = "PlaceName";
        qyd_ddr.DataBind();
        //qyd_ddr.Items.Insert(0, "");
        mdd_ddr.DataSource = new PlaceService().GetEnd();
        mdd_ddr.DataTextField = "PlaceName";
        mdd_ddr.DataBind();
        //mdd_ddr.Items.Insert(0, "");


        statelistdrr.DataSource = new BillStateService().GetAllList();
        statelistdrr.DataTextField = "Description";
        statelistdrr.DataValueField = "BSID";
        statelistdrr.DataBind();
        cplistdrr.DataSource = new DomesticShippingService().GetAll();
        cplistdrr.DataTextField = "CompanyName";
        cplistdrr.DataValueField = "ID";
        cplistdrr.DataBind();

        paylist.DataSource = new PayModelService().GetAll();
        paylist.DataTextField = "ModelName";
        paylist.DataValueField = "PID";
        paylist.DataBind();

    }
    //绑定获取
    void BindHuoWu(string NO)
    {

        DataTable dt = new PublicSqlService().GetData("*", "TblShipment", "TrackingNo='" + NO.Trim() + "'");

        if (dt.Rows.Count > 0)
        {


            if (dt.Rows.Count == 1)
            {
                name1.Value = dt.Rows[0]["Commodity"].ToString();
                num1.Value = dt.Rows[0]["Qty"].ToString();
                price1.Value = dt.Rows[0]["ValueForCustoms"].ToString();


            }
            if (dt.Rows.Count > 1)
            {
                name1.Value = dt.Rows[0]["Commodity"].ToString();
                num1.Value = dt.Rows[0]["Qty"].ToString();
                price1.Value = dt.Rows[0]["ValueForCustoms"].ToString();
                name2.Value = dt.Rows[1]["Commodity"].ToString();
                num2.Value = dt.Rows[1]["Qty"].ToString();
                price2.Value = dt.Rows[1]["ValueForCustoms"].ToString();
            }

        }

    }
    //写入数据
    void ToInsert()
    {



        #region   发送人基本属性


        Hashtable hs = new Hashtable();

        hs.Add("SendBy", sendertxt.Value);
        // hs.Add("FromFaxNo", "");
        hs.Add("USATelNo", phonenotxt.Value);
        hs.Add("USACompany", companytxt.Value);
        hs.Add("USAAddress", addtxt.Value);



        #endregion
        #region   收件人基本属性

        hs.Add("CHNReceiver", renametxt.Value);
        hs.Add("CHNTelNo", rephonenotxt.Value);
        hs.Add("CHNCompany", recompanytxt.Value);
        hs.Add("CHNAddress", readdtxt.Value.Trim());


        #endregion
        #region 其他相关属性



        hs.Add("FlightNo", FlightNotxt.Value);//参考

        hs.Add("AerialNo", AerialNotxt.Value);//航空单号






        hs.Add("Origin", qyd_ddr.SelectedItem.Text);
        hs.Add("Dest", mdd_ddr.SelectedItem.Text);


        //支付方式

        hs.Add("PayType", paylist.SelectedItem.Value);

        //包装形式

        hs.Add("Packing", huowulist.SelectedItem.Value);



        #endregion
        #region 质量 体积

        hs.Add("Weight", tool.StringToDecimalDif(StrHelper.VldNull(zhongliang_txt.Value)));//重重量
        hs.Add("MeasurementH", tool.StringToDecimalDif(StrHelper.VldNull(gaotxt.Value)));
        hs.Add("MeasurementL", tool.StringToDecimalDif(StrHelper.VldNull(changtxt.Value)));
        hs.Add("MeasurementW", tool.StringToDecimalDif(StrHelper.VldNull(kuantxt.Value)));
        hs.Add("Description", Descriptiontxt.Value.Trim());


        hs.Add("DimensionsWeight", tool.StringToDecimalDif(StrHelper.VldNull(tijizhonglianghd.Value)));  //体积重量  起运地为美国

        #endregion
        #region  价格
        hs.Add("ChargedWt", tool.StringToDecimalDif(StrHelper.VldNull(shoufeizhonglianghd.Value)));//收费重量

        hs.Add("FreightCharge", tool.StringToDecimalDif(zlshoufeihd.Value));//重量收费
        hs.Add("TotalMoney", tool.StringToDecimalDif(haiguanhd.Value));//海关申报总价
        hs.Add("Memo2", tool.StringToDecimalDif(dianfufeilb.Value));//垫付费
        hs.Add("Memo3", tool.StringToDecimalDif(daigoufeihd.Value));//代购费
        hs.Add("Memo4", tool.StringToDecimalDif(baozhuangfeihd.Value));//包装费
        hs.Add("Duties", tool.StringToDecimalDif(guanshuitxt.Value));//关税
        hs.Add("Premium", tool.StringToDecimalDif(baoxianfeitxt.Value));//保险费
        hs.Add("OtherCharge", tool.StringToDecimalDif(othertxt.Value));//其他费用
        hs.Add("Memo5", tool.StringToDecimalDif(youhuitxt.Value));//优惠
        hs.Add("Total", tool.StringToDecimalDif(Totalhb.Value));//总费用





        hs.Add("Memo1", paytypehd.Value);//计费类别








        #endregion
        #region  状态

        if (new PublicSqlService().Update(hs, "Tbl_SepBill", "SepNo='" + Request.QueryString["SepNo"].ToString().Trim() + "'"))
        {

            InsertHuowu(Request.QueryString["SepNo"].ToString().Trim());
            new WayBillService().UPBillPrice(Request.QueryString["SepNo"].ToString().Trim());
            Tools.OpenWindow(this, "编辑成功！", Request.Url.ToString());

        }
        else
        {
            Tools.OpenWindow(this, "编辑失败！请重试");
            return;
        }
        #endregion



    }
    #region 获取写入编辑
    private void InsertHuowu(string acc)
    {

        //写入


        new PublicSqlService().Del("TblShipment", "TrackingNo='" + acc.Trim() + "'");
        Shipment sp = new Shipment();
        sp.Commodity = name1.Value;
        sp.TrackingNo = acc;
        if (sp.Commodity.Trim() != "")
        {
            sp.HarmonizedCode = "";
            sp.PostTime = DateTime.Now;
            sp.Qty = new Tools().StringToIntDif(num1.Value);
            sp.UnitValue = 0;
            sp.ValueForCustoms = new Tools().StringToDecimalDif(price1.Value);

            new ShipmentService().Insert(sp);
        }
        if (name2.Value.Trim() != "")
        {

            sp.Commodity = name2.Value;
            sp.HarmonizedCode = "";
            sp.PostTime = DateTime.Now;
            sp.Qty = new Tools().StringToIntDif(num2.Value);
            sp.UnitValue = 0;
            sp.ValueForCustoms = new Tools().StringToDecimalDif(price2.Value);

            new ShipmentService().Insert(sp);
        }


    }
    #endregion
    #region 状态写入
    private void StateInsert(string Tno)
    {
        string state = stateidhd.Value.Trim();
        if (state != "" && state != ",")
        {

            string[] idlist = state.Split(',');
            string[] statenamelist = statenamehd.Value.Trim().Split(',');
            string[] datelist = datehd.Value.Trim().Split(',');
            string[] gongsilist = gongsihd.Value.Trim().Split(',');
            string[] danhaolist = danhaohd.Value.Trim().Split(',');


            string id = "";
            string name = "";

            Hashtable hs = new Hashtable();

            int ok = 0;
            for (int i = 0; i < idlist.Length; i++)
            {

                if (idlist[i].ToString().Trim() != "")
                {


                    hs.Clear();
                    hs.Add("SepNo", Tno);
                    hs.Add("Date", tool.StringToTime(datelist[i].ToString()));
                    hs.Add("SateID", idlist[i].ToString());
                    hs.Add("RecordDate", DateTime.Now);
                    hs.Add("RecorderID", Session["uid"].ToString());
                    hs.Add("CompanyID", tool.StringToIntDif(gongsilist[i]));
                    hs.Add("CompanyNo", danhaolist[i]);
                    if (new PublicSqlService().Insert(hs, "Tbl_BillStateRec"))
                    {
                        id = idlist[i].ToString();
                        name = statenamelist[i].ToString();
                        //写入成功
                        ok++;
                    }

                }


            }
            if (ok > 0)
            {
                //写入成功过。更新总单据状态

                hs.Clear();

                hs.Add("State", id);
                hs.Add("SBState", name);

                new PublicSqlService().Update(hs, "Tbl_SepBill", "SepNo='" + Tno + "'");

                if (id.Trim() != "1")
                {
                    //更新主单状态
                    new WayBillService().UpSatate(Tno);
                }
            }



        }
    }

    //留言写入
    private void InsertLiuyan(string Tno)
    {


        if (liuyanhd.Value.Trim() != "" && liuyanhd.Value.Trim() != ",")
        {

            string[] ly = liuyanhd.Value.Trim().Split(',');
            Hashtable hs = new Hashtable();
            for (int i = 0; i < ly.Length; i++)
            {

                if (ly[i].ToString().Trim() != "")
                {
                    hs.Add("Tno", Tno);
                    hs.Add("Content", ly[i]);
                    hs.Add("PostUser", "公司");
                    hs.Add("UserIsRead", 0);
                    hs.Add("UPEXIsRead", 1);
                    hs.Add("PostDate", DateTime.Now);
                    hs.Add("Attachment", "");//附件
                    hs.Add("PostID", Session["uid"].ToString());

                    new PublicSqlService().Insert(hs, "Tbl_Discuss");


                }
            }

        }


    }
    #endregion
    protected void Okbtn_Click(object sender, ImageClickEventArgs e)
    {
        ToInsert();
    }
    protected void insertly_Click(object sender, ImageClickEventArgs e)
    {

        if (liuyanneirong.Value.Trim() == "")
        {
            Tools.OpenWindow(this, "请输入留言内容");
            return;
        }
        Hashtable hs = new Hashtable();
        hs.Add("Tno", Request.QueryString["tno"]);
        hs.Add("Content", liuyanneirong.Value);
        hs.Add("PostUser", "公司");
        hs.Add("UserIsRead", 0);
        hs.Add("UPEXIsRead", 1);
        hs.Add("PostID", Session["uid"].ToString());
        hs.Add("PostDate", DateTime.Now);

        UploadFile up = new UploadFile("jpg,gif,bmp,doc,xls", 1000, "\\Temp\\");
        string att = "";

        if (imgfier.FileName.Trim() != "")
        {
            if (up.UpLoad(imgfier))
            {
                att = up.FileName;
            }
        }
        hs.Add("Attachment ", att);
        new PublicSqlService().Insert(hs, "Tbl_Discuss");
        BindLiuYan(Request.QueryString["SepNo"].ToString());
        liuyanneirong.Value = "";
    }
    protected void delbtn_Click(object sender, ImageClickEventArgs e)
    {
        TnoInfo tn= new TnoInfo ();
        tn.Name="";
        tn.No=Request.QueryString["SepNo"].ToString().Trim();
        tn.Num=1;
        tn.Sep=true;
        tn.Tno="";
        List<TnoInfo> lslt =new List<TnoInfo> ();
        lslt.Add(tn);
        string  serr="";

        if(new WayBillService().DelBill(lslt,ref serr))
        {
            Response.Redirect("BillManaga.aspx");
        }
        else
        {

            Tools.OpenWindow(this, serr);
        }
    }
}
